﻿using AppSocketModel;
using AppSocketService.Account;
using AppSocketService.Vehicle;
using BCGPSCommon;
using BCGPSMongoData;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AppSocketService.AlarmHistoryPerson
{
    public class AlarmNotifyHistoryPersonService :   ServiceBase, IAlarmNotifyHistoryPersonService
    {
        private MongoDBCommand<AlarmNotifyHistoryDto> mongoCommand = new MongoDBCommand<AlarmNotifyHistoryDto>("AlarmNotifyHistory");
        private readonly AccountDto CurrentAccount;
        private readonly IAccountPersonService accountPersonService;
        private readonly IVehiclePersonService vehiclePersonService; 

        #region 构造函数
        public AlarmNotifyHistoryPersonService(IClaimsAccessor claimsAccesso,IAccountPersonService accountPersonService, IVehiclePersonService vehiclePersonService) : base(claimsAccesso)
        {
            this.accountPersonService = accountPersonService;
            this.vehiclePersonService = vehiclePersonService; 
            CurrentAccount = accountPersonService.GetCurrentAccount();

            if (CurrentAccount == null)
                throw new  Exception("登录账户异常,请重新登录 !!!");
        }

        #endregion


         
        #region 获取报警记录 个人
        public PageableList<AlarmNotifyHistoryDto> GetListPerson(string imei, AlarmType? alarmType, AlarmNotifyType? notifyType, bool? isConfirm, bool isDelete, bool desc, int index, int size)
        {
            if(CurrentAccount.CompanyId>0)
            {
                return GetListCompanyPerson(imei, alarmType, notifyType, isConfirm, isDelete, desc, index, size);
            }
            else
            {
                return GetListOnlyPerson(imei, alarmType, notifyType, isConfirm, isDelete, desc, index, size);
            }
        }
        public PageableList<AlarmNotifyHistoryDto> GetListOnlyPerson(string imei, AlarmType? alarmType, AlarmNotifyType? notifyType, bool? isConfirm, bool isDelete, bool desc, int index, int size)
        {
            index = index > 0 ? index - 1 : 0;
            List<string> wheres = new List<string>();

            if (claimsAccessor.AccountRole == AccountRole.SYSTEM)
            {
            }
            else
            {
                wheres.Add($"CompanyId:{CurrentAccount.CompanyId}");
                wheres.Add($"AccountId:\"{CurrentAccount.AccountId}\"");
            }

            if (!string.IsNullOrWhiteSpace(imei))
                wheres.Add($"IMEI:\"{imei}\"");

            if (alarmType.HasValue)
                wheres.Add($"AlarmType:{(int)alarmType}");

            if (notifyType.HasValue)
                wheres.Add($"NotifyType:{(int)notifyType}");

            if (isConfirm.HasValue)
                wheres.Add($"IsConfirm:{isConfirm.Value.ToString().ToLower()}");

            wheres.Add($"IsDelete:{isDelete.ToString().ToLower()}");


            string str = (wheres.Count > 0) ? "{" + string.Join(" , ", wheres) + "}" : "{Id:\"\"}";

            var pageable = mongoCommand.SelectDocumentsAsync(str, s => s.CreateDateTime, desc, index * size, size).GetAwaiter().GetResult();

            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var item in pageable.Items)
            {
                if (dict.ContainsKey(item.IMEI))
                    item.VehicleNo = dict[item.IMEI];
                else
                {
                    item.VehicleNo = GetVehicleNo(item.IMEI);
                    dict.Add(item.IMEI, item.VehicleNo);
                }
            }

            return pageable;
        }
        public PageableList<AlarmNotifyHistoryDto> GetListCompanyPerson(string imei, AlarmType? alarmType, AlarmNotifyType? notifyType, bool? isConfirm, bool isDelete, bool desc, int index, int size)
        {
            index = index > 0 ? index - 1 : 0;
            List<string> wheres = new List<string>();

            if (string.IsNullOrWhiteSpace(imei))
            {
                if (claimsAccessor.AccountRole == AccountRole.SYSTEM)
                {

                }
                else
                {
                    List<string> list = GetImeiList();
                    if (list.Count > 0)
                    {
                        List<string> imeiWhere = new List<string>();
                        foreach (var item in list)
                        {
                            imeiWhere.Add("\"" + item + "\"");
                        }
                        string str1 = string.Join(" , ", imeiWhere);
                        wheres.Add("IMEI:{$in:[" + str1 + "]}");
                    }
                }
            }
            else
            {
                wheres.Add("IMEI:\""+imei+"\"");
            }

            if (alarmType.HasValue)
                wheres.Add($"AlarmType:{(int)alarmType}");

            if (notifyType.HasValue)
                wheres.Add($"NotifyType:{(int)notifyType}");

            if (isConfirm.HasValue)
                wheres.Add($"IsConfirm:{isConfirm.Value.ToString().ToLower()}");

            wheres.Add($"IsDelete:{isDelete.ToString().ToLower()}");


            string str = (wheres.Count > 0) ? "{" + string.Join(" , ", wheres) + "}" : "{Id:\"\"}";
             
            var pageable = mongoCommand.SelectDocumentsAsync(str, s => s.CreateDateTime, desc, index * size, size).GetAwaiter().GetResult();

            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var item in pageable.Items)
            {
                if (dict.ContainsKey(item.IMEI))
                    item.VehicleNo = dict[item.IMEI];
                else
                {
                    item.VehicleNo = GetVehicleNo(item.IMEI);
                    dict.Add(item.IMEI, item.VehicleNo);
                }
            }

            return pageable;
        }
        private List<string> GetImeiList()
        {
            return vehiclePersonService.GetVehicleList().Select(s => s.IMEI).ToList();
        }
        //获取车号
        private string GetVehicleNo(string imei)
        {
            var dto = vehiclePersonService.GetVehicleByImei(imei);
            if (dto == null)
                return "未绑定";
            else
                return dto.VehicleNo;

        }
        #endregion


        #region 报警确认
        public void AlarmConfirm(string id)
        {
            var update = Builders<AlarmNotifyHistoryDto>.Update
                .Set(s=>s.ConfirmDatetime,BCGPSCommon.MongoDBDateTime.GetNowUtc())
                .Set(s=>s.ConfirmAccountCode,CurrentAccount.AccountCode)
                .Set(s => s.IsConfirm, true);
            mongoCommand.UpdateDocumentAsync(s => s.Id == id, update).GetAwaiter().GetResult();
        }
        public void AlarmConfirm(List<string> list)
        {
            var update = Builders<AlarmNotifyHistoryDto>.Update
                .Set(s => s.ConfirmDatetime, BCGPSCommon.MongoDBDateTime.GetNowUtc())
                .Set(s => s.ConfirmAccountCode, CurrentAccount.AccountCode)
                .Set(s => s.IsConfirm, true);
            foreach (var item in list)
            {
                mongoCommand.UpdateDocumentAsync(s => s.Id == item, update).GetAwaiter().GetResult();
            } 
        }
        #endregion


        public void AlarmConfirm(List<string> list, AlarmType? alarmType, AlarmNotifyType? notifyType)
        {
            foreach (var item in list)
            { 
                if (string.IsNullOrWhiteSpace(item))
                    throw new ArgumentException("缺少参数:IMEI");
            }

            foreach (var item in list)
            {
                AlarmConfirm(item, alarmType, notifyType);
            }
        }
        public void AlarmConfirm(string imei, AlarmType? alarmType, AlarmNotifyType? notifyType)
        {
            List<string> wheres = new List<string>();

            if (string.IsNullOrWhiteSpace(imei))
                throw new ArgumentException("缺少参数:IMEI");


            wheres.Add("IMEI:\"" + imei + "\"");
             
            wheres.Add($"IsConfirm:false");

            wheres.Add($"IsDelete:false");

            if (alarmType.HasValue)
                wheres.Add($"AlarmType:{(int)alarmType}");

            if (notifyType.HasValue)
                wheres.Add($"NotifyType:{(int)notifyType}");

            string str = "{"+ string.Join(" , ", wheres) + "}";


            var update = Builders<AlarmNotifyHistoryDto>.Update
                .Set(s => s.ConfirmDatetime, BCGPSCommon.MongoDBDateTime.GetNowUtc())
                .Set(s => s.ConfirmAccountCode, CurrentAccount.AccountCode)
                .Set(s => s.IsConfirm, true);
            mongoCommand.UpdateDocumentsAsync(str, update).GetAwaiter().GetResult();

        }
    }
}
